package club.pchome.controller;

import java.util.Date;
import java.util.List;

import club.pchome.dto.Result;
import club.pchome.util.DateUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import club.pchome.ex.NormalException;
import club.pchome.model.User;
import club.pchome.service.AutoSignService;
import club.pchome.util.EasyPoiUtils;

@RestController
public class FileContoller extends BaseController{

	@Autowired
	AutoSignService autoSignService;
	
	@PostMapping("/importExcel")
	@ResponseBody
    public Result<String> importExcel() throws NormalException{
        String filePath = "E:\\adm_1.xlsx";
        //解析excel，
        List<User> personList = EasyPoiUtils.importExcel(filePath,0,1,User.class);
        //也可以使用MultipartFile,使用 FileUtil.importExcel(MultipartFile file, Integer titleRows, Integer headerRows, Class<T> pojoClass)导入
		int num = 0;
        for (User user : personList) {
			if(user.getPhone() != null) {
				//写入之前判断是否存在
				long count = autoSignService.getUserDataByPhone(user);
				if(count > 0) {
					System.out.println("该手机号已经存在 , phone :" + user.getPhone());
				}else {
					long status = autoSignService.insert(user);
					if(status > 0) {
						num++;
					}else {
						System.out.println("写入失败 , 手机号 : " + user.getPhone());
					}
				}
			}
			
		}
		logger.info("导入数据一共【"+ num +"】行" + DateUtil.FMT_FN.format(new Date()));
	 	return Result.initSuccessResult("导入数据一共【"+ num +"】行");
    }
}
